package com.example.bank.shiro.realm;

import com.example.bank.pojo.User;
import com.example.bank.service.user.UserService;
import com.example.bank.shiro.token.JWTToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @author ：Leeziqiang
 * @description：TODO
 * @date ：2021/11/21 17:36
 */
@Component
public class JWTRealm extends AuthorizingRealm {

    @Autowired
    private UserService serice;
    // 限定这个Realm只处理我们自定义的JWTToken
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    // 此处的SimpleAuthenticationInfo 可返回任意值，密码校验时不会用到它
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JWTToken jwtToken = (JWTToken) authenticationToken;
        if (jwtToken.getPrincipal() == null) {
            throw new AccountException("JWT Token参数异常！");
        }
        // 从JWT Token中获取当前用户
        String id = jwtToken.getPrincipal().toString();
        // 查询数据库获取用户信息，此处使用Map来模拟数据库
        User user = serice.getById(id);
        // 用户不存在
        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, id, getName());
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取当前用户
        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
        // 查询数据库，获取用户的角色信息
        Set<String> roles = new HashSet<String>();
        String role = serice.findRoleByUserId(currentUser.getUserId());
        roles.add(role);
        // 查询数据库获取用户的权限信息
        Set<String> perms = new HashSet<String>();
        String perm = serice.findPermByUserId(currentUser.getUserId());
        perms.add(perm);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(perms);
        return info;
    }


}
